package com.zgj.netty_udp.server;

import com.zgj.netty_udp.dao.TempRecordMapper;
import com.zgj.netty_udp.model.TempRecord;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

@Component
@Slf4j
public class MessageProcessor implements Runnable {
    @Autowired
    private TempRecordMapper tempRecordMapper;

    public MessageProcessor() {
        new Thread(this).start();
    }

    private BlockingQueue<Message> queue = new ArrayBlockingQueue<>(30000);

    void produce(Channel channel, byte[] msg) throws InterruptedException {
        if (!queue.offer(new Message(channel, msg))) {
            log.info("MessageManager length = " + queue.size());
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                msgProc(queue.take());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void msgProc(Message message) {
        Channel channel = message.getChannel();
        if (channel != null && channel.isActive() && channel.isOpen()) {

            procMsg(channel, message.getMsg());
        }
    }

    private void procMsg(Channel channel, byte[] msg) {
        //todo
        log.info("开始存储数据");
        TempRecord tempRecord = new TempRecord();
        tempRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        String message = BinaryToHexString(msg);
        System.out.println(message);
        tempRecord.setCrc16(message);
//        byte[] bytes = {-114, 125, 39, 0, 1, 0, 46, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 25, 0, 1, 26, 0, 2, 27, 0, 3, 28, 0, 4, 29, 0, -28, 88};
        tempRecord.setProVer((msg[4] & 0xff) + "");
        tempRecord.setUpload((msg[5] & 0xff) + "");
        tempRecord.setSeqno((msg[6] & 0xff) + "");
        tempRecord.setManNum((msg[8] & 0xff) + "");
        tempRecord.setDevId((msg[10] & 0xff )+ "");
        tempRecordMapper.insert(tempRecord);
        log.info("业务处理完成");
    }

    protected static char HEX_CHAR[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static String BinaryToHexString(byte[] bytes) {

        StringBuilder sb = new StringBuilder();
        int num;
        for (byte b : bytes) {
            num = b < 0 ? 256 + b : b;
            sb.append(HEX_CHAR[num / 16]).append(HEX_CHAR[num % 16]);
        }
        return sb.toString();
    }
}
